<template>
	<el-dialog
		title="提示"
		:visible.sync="dialogVisible"
		width="40%"
		:before-close="handleClose"
		style="text-align:left;"
	>
		<el-form :model="roleInfo" :rules="rules" ref="roleInfo">
			<table>
				<tr>
					<td>角色名称</td>
					<td>
						<el-form-item prop="roleName">
							<el-input v-model="roleInfo.roleName"></el-input>
						</el-form-item>
					</td>
				</tr>
				<tr>
					<td>角色描述</td>
					<td>
						<el-form-item prop="roleDesc">
							<el-input v-model="roleInfo.roleDesc"></el-input>
						</el-form-item>
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<el-row>
							<el-tree
								:data="allPermissions"
								show-checkbox
								node-key="permissionDesc"
								ref="tree"
								:props="defaultProps"
							>	
							</el-tree>
						</el-row>
					</td>
				</tr>
			</table>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="$parent.showAddNewRole = false">取消</el-button>
			<el-button type="primary" @click="addNewOne">确定</el-button>
		</span>
	</el-dialog>
</template>

<script>
	export default{
		data(){
			return{
				dialogVisible:true,
				defaultProps:{
					children:'children',
					label:'permissionDesc',
				},
				roleInfo:{roleName:'',roleDesc:'',permissions:[]},
				rules:{
					roleName:[
						{required:true,message:'请输入角色名称',trigger:'blur'},
						{min:3,max:20,message:'角色名长度在3到20个字符',trigger:'blur'},
					],
					roleDesc:[
						{required:true,message:'请输入角色描述',trigger:'blur'},
						{min:3,max:20,message:'角色描述长度在3到20个字符',trigger:'blur'},
					]
				}
			}
		},
		computed:{
			allPermissions(){
//				console.log(this.$store.getters.allPermissions);  得到的是obj,所以要转换成数组
//				return this.$store.getters.allPermissions;
				var Arr = [];
				var obj = this.$store.getters.allPermissions;
				for(var key in obj){
					Arr.push(obj[key])
				}
				return Arr;
			}
		},
		mounted(){
//			console.log(this.$store.dispatch("allRoles"))
			this.$store.dispatch("allRoles");
		},
		methods:{
			handleClose(){
				this.$parent.showAddNewRole = false;
			},
			addNewOne(){
				var permission = [];
				this.$refs.tree.getCheckedNodes().forEach((item)=>{
					permission.push(item._id)
				})
				this.roleInfo.permissions=permission;
				this.$refs['roleInfo'].validate((valid)=>{
					if(valid){
						this.$http.post(this.$apis.addRole,this.roleInfo)
						.then((resp)=>{
							this.$message({
								message:resp.message,
								type:resp.success?"success":"danger"
							});
							this.handleClose();
							this.$store.dispatch("allRoles",{api:this.$api.allRoles});
						})
					}else{
						console.log('error submit');
						return false;
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	
</style>